//
//  NSDictionary+Safe.m
//  NWBaseKit
//
//  Created by Seven on 2017/5/19.
//  Copyright © 2017年 Niuwa. All rights reserved.
//

#import "NSDictionary+Safe.h"

@implementation NSDictionary (Safe)
- (id)safeObjectForKey:(NSString *)key {
    if (key == nil || [self isKindOfClass:[NSNull class]]) {
        return nil;
    }
    id object = [self objectForKey:key];
    if (object==nil || object == [NSNull null]) {
        return @"";
    }
    return object;
}


- (void)safeSetObject:(id)object forKey:(id)key {
    if ([key isKindOfClass:[NSNull class]]) {
        return;
    }
    if ([object isKindOfClass:[NSNull class]]) {
        [self setValue:@"" forKey:key];
    }else{
        [self setValue:object forKey:key];
    }
}

- (id)objectForKeyCustom:(id)aKey {
    id object   = nil;
    
    // 检查是否字典对象
    if (![self isKindOfClass:[NSDictionary class]]) {
        return object;
    }
    
    // 保证key必须为字符串
    if (aKey && [aKey isKindOfClass:[NSString class]]) {
        object  = [self objectForKeyCustom:aKey];
    }
    
    return object;
}

- (id)safeKeyForValue:(id)value {
    for (id key in self.allKeys) {
        if ([value isEqual:[self objectForKey:key]]) {
            return key;
        }
    }
    return nil;
}

+ (id)coverFromUrlParamsString:(NSString *)paramsString{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    NSString *tmpStr = paramsString;
    NSRange range = [tmpStr rangeOfString:@"?"];
    if (range.location != NSNotFound) {
        tmpStr = [tmpStr safeSubstringFromIndex:range.location+1];
    }
    NSArray *tmp = [tmpStr componentsSeparatedByString:@"&"];
    for (NSString *param in tmp) {
        NSArray *paramTmp = [param componentsSeparatedByString:@"="];
        if (paramTmp.count==2) {
            dic[paramTmp.firstObject]=paramTmp.lastObject;
        }
    }
    return dic;
}

- (NSString *)coverToUrlParamsString{
    NSMutableString *paramsString = [NSMutableString string];
    [self enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        [paramsString appendFormat:@"%@=%@&",key, obj];
    }];
    if (paramsString.length > 1) {
        [paramsString deleteCharactersInRange:NSMakeRange(paramsString.length-1, 1)];
    }
    
    return paramsString;
}

@end
